#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>

// (复用 sm4_openssl.c 中的 print_hex 函数)
void print_hex(const char* label, const unsigned char* data, int len) {
    printf("%s (%d bytes):\n", label, len);
    for (int i = 0; i < len; ++i) {
        printf("%02x", data[i]);
    }
    printf("\n");
}

int main() {
    EVP_MD_CTX *md_ctx;
    const EVP_MD *md;
    unsigned char md_value[EVP_MAX_MD_SIZE];
    unsigned int md_len;

    const unsigned char msg[] = "Test message for SM3 hash";

    // 1. SM3 摘要计算
    // OpenSSL 3.x 使用 EVP_sm3()
    md = EVP_sm3();
    if (md == NULL) {
        fprintf(stderr, "EVP_sm3() not found\n");
        return 1;
    }

    md_ctx = EVP_MD_CTX_new();
    EVP_DigestInit_ex(md_ctx, md, NULL);
    EVP_DigestUpdate(md_ctx, msg, strlen((char*)msg));
    EVP_DigestFinal_ex(md_ctx, md_value, &md_len);
    EVP_MD_CTX_free(md_ctx);

    print_hex("SM3 Hash", md_value, md_len);

    // 2. SM3 HMAC 计算
    const unsigned char key[] = "mysecretkey";
    unsigned char hmac_value[EVP_MAX_MD_SIZE];
    unsigned int hmac_len;

    // HMAC() 是一个便捷的封装函数
    HMAC(md, key, strlen((char*)key), msg, strlen((char*)msg), hmac_value, &hmac_len);
    
    print_hex("SM3 HMAC", hmac_value, hmac_len);

    printf("SM3 Hash and HMAC calculation complete.\n");

    return 0;
}
